#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <netdb.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <signal.h>
#include <sys/wait.h>

# include <sys/stat.h>
# include <sys/mman.h>

#define MAXLINE 100
#define SERV_PORT 9006
/*
int date_time_update()
{
	struct sockaddr_in servaddr;
	char buf[MAXLINE];
	int sockfd, n;
	struct timeval outtime;
	struct stat stat;
	struct hostent *host;
	char dt_cmd[40];
	
	memset(dt_cmd, 0, 40);
	strcpy(dt_cmd, "date 20");

	memset(buf,0,MAXLINE);
	
	if(NULL == (host=gethostbyname("ems.muxvision.com")))
	{
		return -1;
	}

	sockfd = socket(AF_INET, SOCK_STREAM, 0);
	outtime.tv_sec = 5;
	outtime.tv_usec = 0;
	setsockopt(sockfd, SOL_SOCKET,SO_RCVTIMEO, &outtime,sizeof(outtime));
	bzero(&servaddr, sizeof(servaddr));
	servaddr.sin_family = AF_INET;

	servaddr.sin_addr = *((struct in_addr *)host->h_addr);
	//inet_pton(AF_INET, "192.168.2.117", &servaddr.sin_addr);
	//printf("address:%s\n", inet_ntop(AF_INET,host->h_addr, buf, sizeof(buf)));

	servaddr.sin_port = htons(SERV_PORT);
	
	printf("connect...\n");
	connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr));

	memset(buf,0,MAXLINE);
	if((n = read(sockfd, buf, MAXLINE)) < 16)
	return -1;
	buf[n-4] = '\0';

	buf[2]='.';
	buf[5]='.';
	buf[8]='-';
	buf[11]=':';
	buf[14]=':';

	strcat(dt_cmd,buf);
	system(dt_cmd);
	system("hwclock -w");
	close(sockfd);
	return 0;
	
}
*/

int date_time_update()
{
    pid_t child, status;
    if ((child = fork()) < 0) {
        perror("fork");
        return -1;
    }
    if(child == 0){
        execlp("./time_update" , "" , NULL);
        return -1;
    } else {
        	if(wait(&status) < 0) {
            	perror("wait");
            	exit(1);
      	  }
    }
    return status;
}

int main(int argc, char *argv[])
{
	while(1)
	{
		date_time_update();
		sleep(300);
	}
	return 0;
}
